package com.lhj.library.domain.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.lhj.library.common.constant.RoleConstant;
import com.lhj.library.common.enums.IsDeletedFlagEnum;
import com.lhj.library.common.enums.IsDisabledFlagEnum;
import com.lhj.library.domain.convert.UserBoConverter;
import com.lhj.library.domain.entity.UserBO;
import com.lhj.library.domain.service.AuthDomainService;
import com.lhj.library.infra.basic.entity.Role;
import com.lhj.library.infra.basic.entity.User;
import com.lhj.library.infra.basic.entity.UserRole;
import com.lhj.library.infra.basic.service.RoleService;
import com.lhj.library.infra.basic.service.UserRoleService;
import com.lhj.library.infra.basic.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

@Service
@Slf4j
public class AuthDomainServiceImpl implements AuthDomainService {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private UserRoleService userRoleService;

    private String salt = "nailong";

    @Override
    public Boolean register(UserBO userBO) {
        if (log.isInfoEnabled()) {
            log.info("AuthController.register.bo:{}", JSON.toJSONString(userBO));
        }
        User user = UserBoConverter.INSTANCE.convertBoToBook(userBO);
        user.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        user.setStatus(IsDisabledFlagEnum.UN_DISABLED.getCode());
        user.setPassword(SaSecureUtil.md5BySalt(userBO.getPassword(), salt));
        user.setName(String.valueOf(UUID.randomUUID()));
        userService.insert(user);
        //给注册用户添加初始角色
        Role role = new Role();
        role.setRoleName(RoleConstant.NORMAL_USER);
        Role queryRole = roleService.queryByCondition(role);
        Long roleId = queryRole.getId();
        Long userId = user.getId();
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        userRole.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        int result = userRoleService.insert(userRole);
        return result > 0;
    }

    @Override
    public void login(UserBO userBO) {
        if (log.isInfoEnabled()) {
            log.info("AuthController.login.bo:{}", JSON.toJSONString(userBO));
        }
        User user = new User();
        user.setStudentId(userBO.getStudentId());
        User queryUser = userService.queryByCondition(user);
        if (queryUser != null) {
            if (!SaSecureUtil.md5BySalt(userBO.getPassword(), salt).equals(queryUser.getPassword())) {
                throw new RuntimeException("账号或密码错误");
            }
            StpUtil.login(queryUser.getId());
        }

    }
}
